package com.happy3w.bean;

import com.happy3w.bean.factory.TypeDetector;
import com.happy3w.java.ext.Pair;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Stream;

@Slf4j
public class DefaultTypeDetector implements TypeDetector {

    /**
     * 在packageSampleType所在package下扫描所有types类型的子类
     * @param packageSampleType 带扫描package类型
     * @param types 需要扫描的类型
     * @return key为types，value为找到的子类
     */
    public Stream<Pair<Class, Class>> detect(Class packageSampleType, Class... types) {
        String packageName = packageSampleType.getPackage().getName();
        return detect(packageName, types);
    }

    public Stream<Pair<Class, Class>> detect(String packageName, Class... types) {
        log.info("scan package:{}", packageName);
        Reflections reflections = new Reflections(packageName);
        return Arrays.asList(types).stream()
                .flatMap(type -> {
                    Set<Class> subTypes = reflections.getSubTypesOf(type);
                    return subTypes.stream().map(subType -> Pair.of(type, subType));
                });
    }
}
